<template>
  <view class="login-container">
    <text class="title">用户登录</text>

    <input class="input" v-model="phone" placeholder="请输入手机号" />
    <input class="input" v-model="password" placeholder="请输入密码" password />

    <button class="btn" @click="handleLogin">登录</button>
    <text class="link" @click="goRegister">没有账号？去注册</text>
  </view>
</template>

<script setup>
import { ref } from 'vue'
// 导入登录接口和获取用户信息接口
import { login, getGuestInfo ,getWorkerInfo} from '../../utils/userApi.js'

const phone = ref('')
const password = ref('')

// 登录处理函数
const handleLogin = async () => {
  if (!phone.value || !password.value) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' })
    return
  }

  try {
    //调用登录接口获取 token
    const res = await login({ phone: phone.value, password: password.value })

    if (res.token) {
      //登录成功，先存 token
      uni.setStorageSync('token', res.token)
      uni.setStorageSync('role', res.role) //  保存角色信息
	  await new Promise(r => setTimeout(r, 50))
	  let userRes = null
      //调用获取用户信息接口
	  if (res.role === 'Worker') {
	    userRes = await getWorkerInfo()  // 管理员接口
	  } else if (res.role === 'Guest') {
	    userRes = await getGuestInfo()  // 志愿者接口
	  } 

      if (userRes) {
        // 存储用户信息到本地
        uni.setStorageSync('userInfo', userRes)
        uni.showToast({ title: '登录成功', icon: 'success' })

        //登录成功后跳转首页
        uni.reLaunch({ url: '/pages/home/home' })
      } else {
        uni.showToast({ title: userRes.message || '获取用户信息失败1', icon: 'none' })
      }
    } else {
      uni.showToast({ title: res.message || '登录失败', icon: 'none' })
    }
  } catch (e) {
    console.error(e)
    uni.showToast({ title: '网络或服务器错误', icon: 'none' })
  }
}

// 跳转注册页
const goRegister = () => {
  uni.navigateTo({ url: '/pages/login/register' })
}
</script>

<style>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 50rpx;
}

.input {
  width: 80%;
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.btn {
  width: 80%;
  background-color: #007aff;
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
  margin-top: 20rpx;
}

.link {
  margin-top: 40rpx;
  color: #007aff;
}
</style>
